#!/usr/bin/python
# -*- coding: utf-8 -*-
#encoding=utf-8
#Filename: watch-yongfu-project.py

import urllib2
import smtplib, time
from email.mime.text import MIMEText

def checkUrl(url, host = ''):
    response = None
    try:
        req = urllib2.Request(url)
        if len(host) != 0:
            req.add_header('Host', host)
        response = urllib2.urlopen(req, timeout=5)
    except urllib2.URLError as e:
        if hasattr(e, 'code'):
            res = 1
            msg = 'Error code:', e.code
        elif hasattr(e, 'reason'):
            res = 2
            msg = 'Reason:', e.reason
    finally:
        if response:
            res = 0
            msg = 'success'
            response.close()
        else:
            res = 3
            msg = 'failed for unknown reason'
    #print msg
    return res, msg

def sendMail(subject, mail_body):
    # 发信邮箱
    mail_from = 'postmaster@hunantv02.sendcloud.org'
    # 收信邮箱
    mail_to = ['liaoyongfu@e.hunantv.com']
    # 定义正文
    msg = MIMEText(mail_body)
    # 定义标题
    msg['Subject'] = '[警报]' + subject
    # 定义发信人
    msg['From'] = 'hunantv'
    msg['To'] = ';'.join(mail_to)
    # 定义发送时间（不定义的可能有的邮件客户端会不显示发送时间）
    msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')

    smtp=smtplib.SMTP()
    # 连接SMTP服务器
    smtp.connect('smtpcloud.sohu.com')
    # 用户名密码
    smtp.login(mail_from, 'CpyMUoZe')
    smtp.sendmail(mail_from,mail_to,msg.as_string())
    smtp.quit()

watch_url = [{'name':'wiki', 'url':'http://10.1.172.105/doku.php'},
             {'name':'sdk', 'url':'http://115.182.70.66', 'host':'sdk.mpp.hunantv.com'},
             {'name':'sentry', 'url':'http://54.223.141.233:9000/auth/login/'}]

res, msg = (0, '')
for index in watch_url:
    host = ''
    if index.has_key('host'):
        host = index['host']
    res, msg = checkUrl(index['url'], host)


    # 判断返回值是否为 0，如果不为0，则再执行一次，减少误报
    if res != 0:
        res, msg = checkUrl(index['url'], host)

    # 如果两次执行结果都显示有错误，则触发警报
    if res != 0:
        subject = index['name'] + ' service Error ' + time.strftime('%H:%M:%S')

        # 邮件正文
        msgTime = 'DateTime: ' + time.strftime('%Y-%m-%d %H:%M:%S') + "\n"
        msgService = 'Service: ' + index['name'] + "\n"
        msgUrl = 'Url: ' + index['url'] + "\n"
        msgError = 'Error: ' + msg + "\n"
        mailBody = msgError + msgTime + msgService + msgUrl

        sendMail(subject, mailBody)
